#!/usr/bin/env python
#from svmutil import *
from libsvm.python.svmutil import *
from dataset.DatasetImplementations import DatasetForLibSVM

class SVM:

	def __init__(self):
		pass

	def train(self, claim_list):
		X=[]
		Y=[]
		for claim in claim_list:
			X.append(claim.sparse_data())
			Y.append( claim.get_numerical_category())
		print 'entrenando SVM...'
		self.model = svm_train(Y, X, '-c 512 -t 2 -g 0.000122070')

	def test(self, claim_list):
		X_test=[]
		Y_test=[]
		for claim in claim_list:
			X_test.append(claim.sparse_data())
			Y_test.append( claim.get_numerical_category())
		print 'testing SVM...'
		p_labels, p_acc, p_vals =  svm_predict(Y_test, X_test, self.model)
		#print p_labels
		#print p_acc
		#print p_vals
		return p_acc

	def print_confusition_matriz(self, claim_list):
		print 'labels ', self.model.get_labels()
		for claim in claim_list:
			x0, max_idx = gen_svm_nodearray(claim.sparse_data())
			label = libsvm.svm_predict(self.model, x0)
			print label


	def get_support_vectors(self):
		return self.model.get_SV()


if __name__ == '__main__':
	data = DatasetForLibSVM()
	#data.create_new_datasets()
	svm = SVM()
	trainig_set = data.get_training_set()
	#print trainig_set[0].X
	trainig_set.extend(data.get_validation_set())
	svm.train(trainig_set)
	print 'Probando SVM...'
	acurracy= svm.test(trainig_set)
	print 'acurracy for training set: ',acurracy
	acurracy= svm.test(data.get_test_set())
	print 'acurracy for test set: ',acurracy
	#print 'vocabulary size ', len(svm.V)
	svm.print_confusition_matriz(data.get_test_set())